import React, { useState } from 'react';


const flatData = [
  { id: 1, name: ' 1', parentId: null },
  { id: 2, name: '1-1', parentId: 1 },
  { id: 3, name: '1-2', parentId: 1 },
  { id: 4, name: '1-1-1', parentId: 2 },
  { id: 5, name: ' 2', parentId: null },
  { id: 6, name: ' 2-1', parentId: 5 },
];


const buildTree = (data) => {
  const tree = [];
  const map = {};

  data.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  data.forEach(item => {
    if (item.parentId === null) {
      tree.push(map[item.id]);
    } else {
      map[item.parentId].children.push(map[item.id]);
    }
  });

  return tree;
};


const TreeMenu = () => {
  const [treeData] = useState(buildTree(flatData));
  

  const [expandedKeys, setExpandedKeys] = useState({});

  const toggleExpand = (id) => {
    setExpandedKeys(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };

  const renderTree = (nodes) => {
    return nodes.map(node => (
      <div key={node.id} style={{ marginLeft: '20px' }}>
        <div onClick={() => toggleExpand(node.id)} style={{ cursor: 'pointer' }}>
          {node.name} {expandedKeys[node.id] ? '-' : '+'}
        </div>
        {expandedKeys[node.id] && node.children.length > 0 && (
          <div>{renderTree(node.children)}</div>
        )}
      </div>
    ));
  };

  return (
    <div>
      <h1>树形菜单</h1>
      {renderTree(treeData)}
    </div>
  );
};

export default TreeMenu;